package com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.repository.entity.HddcGeomorphypolygonEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.repository.HddcGeomorphypolygonNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.repository.HddcGeomorphypolygonRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.service.HddcGeomorphypolygonService;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.viewobjects.HddcGeomorphypolygonQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeomorphypolygon.viewobjects.HddcGeomorphypolygonVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-09
 */
@Service
public class HddcGeomorphypolygonServiceImpl implements HddcGeomorphypolygonService {

	@Autowired
    private HddcGeomorphypolygonRepository hddcGeomorphypolygonRepository;
    @Autowired
    private HddcGeomorphypolygonNativeRepository hddcGeomorphypolygonNativeRepository;

    @Override
    public JSONObject queryHddcGeomorphypolygons(HddcGeomorphypolygonQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeomorphypolygonEntity> hddcGeomorphypolygonPage = this.hddcGeomorphypolygonNativeRepository.queryHddcGeomorphypolygons(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeomorphypolygonPage);
        return jsonObject;
    }


    @Override
    public HddcGeomorphypolygonEntity getHddcGeomorphypolygon(String id) {
        HddcGeomorphypolygonEntity hddcGeomorphypolygon = this.hddcGeomorphypolygonRepository.findById(id).orElse(null);
         return hddcGeomorphypolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphypolygonEntity saveHddcGeomorphypolygon(HddcGeomorphypolygonEntity hddcGeomorphypolygon) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeomorphypolygon.setUuid(uuid);
        hddcGeomorphypolygon.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphypolygon.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeomorphypolygon.setIsValid("1");
        hddcGeomorphypolygon.setQualityinspectionStatus("0");
        hddcGeomorphypolygon.setExtends10("1");
        this.hddcGeomorphypolygonRepository.save(hddcGeomorphypolygon);
        return hddcGeomorphypolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeomorphypolygonEntity> saveHddcGeomorphypolygonList(List<HddcGeomorphypolygonEntity> list) {
        for (HddcGeomorphypolygonEntity hddcGeomorphypolygon : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeomorphypolygon.setUuid(uuid);
            hddcGeomorphypolygon.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeomorphypolygon.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeomorphypolygon.setIsValid("1");
            hddcGeomorphypolygon.setQualityinspectionStatus("0");
            hddcGeomorphypolygon.setExtends10("1");
        }
        return hddcGeomorphypolygonNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphypolygonEntity updateHddcGeomorphypolygon(HddcGeomorphypolygonEntity hddcGeomorphypolygon) {
        HddcGeomorphypolygonEntity entity = hddcGeomorphypolygonRepository.findById(hddcGeomorphypolygon.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeomorphypolygon);
        hddcGeomorphypolygon.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphypolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeomorphypolygonRepository.save(hddcGeomorphypolygon);
        return hddcGeomorphypolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeomorphypolygons(List<String> ids) {
        List<HddcGeomorphypolygonEntity> hddcGeomorphypolygonList = this.hddcGeomorphypolygonRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphypolygonList) && hddcGeomorphypolygonList.size() > 0) {
            for(HddcGeomorphypolygonEntity hddcGeomorphypolygon : hddcGeomorphypolygonList) {
                hddcGeomorphypolygon.setIsValid("0");
                hddcGeomorphypolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphypolygon.setUpdateTime(new Date());
                this.hddcGeomorphypolygonRepository.save(hddcGeomorphypolygon);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeomorphypolygonQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeomorphypolygonEntity> yhDisasterEntities = hddcGeomorphypolygonNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeomorphypolygonVO> list=new ArrayList<>();
        for (HddcGeomorphypolygonEntity entity:yhDisasterEntities) {
            HddcGeomorphypolygonVO yhDisasterVO=new HddcGeomorphypolygonVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地貌面-面","地貌面-面",HddcGeomorphypolygonVO.class,"地貌面-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeomorphypolygonVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeomorphypolygonVO.class, params);
            List<HddcGeomorphypolygonVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeomorphypolygonVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeomorphypolygonVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeomorphypolygonVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeomorphypolygonEntity yhDisasterEntity = new HddcGeomorphypolygonEntity();
            HddcGeomorphypolygonVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeomorphypolygon(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeomorphypolygonEntity> hddcGeomorphypolygonList = this.hddcGeomorphypolygonRepository.queryHddcGeomorphypolygonsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphypolygonList) && hddcGeomorphypolygonList.size() > 0) {
            for(HddcGeomorphypolygonEntity hddcGeomorphypolygon : hddcGeomorphypolygonList) {
                hddcGeomorphypolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphypolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphypolygon.setIsValid("0");
                this.hddcGeomorphypolygonRepository.save(hddcGeomorphypolygon);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeomorphypolygonEntity> hddcGeomorphypolygonList = this.hddcGeomorphypolygonRepository.queryHddcGeomorphypolygonsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphypolygonList) && hddcGeomorphypolygonList.size() > 0) {
            for(HddcGeomorphypolygonEntity hddcGeomorphypolygon : hddcGeomorphypolygonList) {
                hddcGeomorphypolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphypolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphypolygon.setIsValid("0");
                this.hddcGeomorphypolygonRepository.save(hddcGeomorphypolygon);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeomorphyCode")){
            str+="GeomorphyCode,";
        }
        if(!set.contains("GeomorphyName")){
            str+="GeomorphyName,";
        }
        if(!set.contains("GeomorphyType")){
            str+="GeomorphyType,";
        }
        if(!set.contains("GeomorphyDescription")){
            str+="GeomorphyDescription,";
        }
        if(!set.contains("Length")){
            str+="Length,";
        }
        if(!set.contains("width")){
            str+="width,";
        }
        if(!set.contains("Height")){
            str+="Height,";
        }
        if(!set.contains("MaxVerticalDisplacement")){
            str+="MaxVerticalDisplacement,";
        }
        if(!set.contains("MaxHorizenOffset")){
            str+="MaxHorizenOffset,";
        }
        if(!set.contains("MaxTDisplacement")){
            str+="MaxTDisplacement,";
        }
        if(!set.contains("Feature")){
            str+="Feature,";
        }
        if(!set.contains("CreateDate")){
            str+="CreateDate,";
        }
        if(!set.contains("IsSurfaceRuptureBelt")){
            str+="IsSurfaceRuptureBelt,";
        }
        if(!set.contains("FractureType")){
            str+="FractureType,";
        }
        if(!set.contains("Photo_AIID")){
            str+="Photo_AIID,";
        }
        if(!set.contains("Photo_ARWID")){
            str+="Photo_ARWID,";
        }

        if(!set.contains("PhotoViewingTo")){
            str+="PhotoViewingTo,";
        }
        if(!set.contains("Photographer")){
            str+="Photographer,";
        }
        if(!set.contains("nsb1")){
            str+="nsb1,";
        }
        if(!set.contains("nsb2")){
            str+="nsb2,";
        }
        if(!set.contains("nsb3")){
            str+="nsb3,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;

    }

    @Override
    public void savehddcGeomorphypolygonServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcGeomorphypolygonEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeomorphypolygonEntity data = new HddcGeomorphypolygonEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphycode(obs.get(2).toString());
                data.setGeomorphyname(obs.get(3).toString());
                data.setGeomorphytype(obs.get(4).toString());
                data.setGeomorphydescription(obs.get(5).toString());
                data.setLength(Double.valueOf(obs.get(6).toString()));
                data.setWidth(Double.valueOf(obs.get(7).toString()));
                data.setHeight(Double.valueOf(obs.get(8).toString()));
                data.setMaxverticaldisplacement(Double.valueOf(obs.get(9).toString()));
                data.setMaxhorizenoffset(Double.valueOf(obs.get(10).toString()));
                data.setMaxtdisplacement(Double.valueOf(obs.get(11).toString()));
                data.setFeature(obs.get(12).toString());
                data.setCreatedate(Integer.valueOf(obs.get(13).toString()));
                data.setIssurfacerupturebelt(Integer.valueOf(obs.get(14).toString()));
                data.setFracturetype(Integer.valueOf(obs.get(15).toString()));
                data.setPhotoAiid(obs.get(16).toString());
                data.setPhotoArwid(obs.get(17).toString());
                data.setPhotoviewingto(Integer.valueOf(obs.get(18).toString()));
                data.setPhotographer(obs.get(19).toString());
                data.setNsb1(obs.get(20).toString());
                data.setNsb2(obs.get(21).toString());
                data.setNsb3(obs.get(22).toString());
                data.setCommentInfo(obs.get(23).toString());
                data.setExtends16("CGCS2000");
                /*String pstr=obs.get(0).toString();
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                String pstr=obs.get(0).toString();
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeomorphypolygonList(datas);
        }

    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeomorphypolygonEntity> hddcGeomorphypolygonList = this.hddcGeomorphypolygonRepository.queryHddcGeomorphypolygonByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphypolygonList) && hddcGeomorphypolygonList.size() > 0) {
            hddcGeomorphypolygonRepository.deleteAll(hddcGeomorphypolygonList);
        }
    }


    @Override
    public List<HddcGeomorphypolygonEntity> findAll() {
        List<HddcGeomorphypolygonEntity> list=this.hddcGeomorphypolygonRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeomorphypolygonRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

}
